//
//  MZValidateTool.swift
//  MZTool
//
//  Created by gby on 2023/1/28.
//

import Foundation

public class MZValidateTool {
    static let validate_code_telphone = "^1{1}\\d{10}$"
    static let validate_code_idcard =  "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)\\$"
    static let validate_code_enterprise_15 = "^[0-9]{15}$"
    static let validate_code_enterprise_18 = "^[A-Za-z0-9]{18}$"
    
    
    
    public static func validateMobile(_ phone: String) -> Bool{
        let predicate = NSPredicate.init(format: "SELF MATCHES %@", MZValidateTool.validate_code_telphone)
        return predicate.evaluate(with: phone)
    }
    
    public static func validateIDCard(_ idcard: String) -> Bool{
        let predicate = NSPredicate.init(format: "SELF MATCHES %@", MZValidateTool.validate_code_idcard)
        return predicate.evaluate(with: idcard)
    }
    
    public static func validateEnterpriseCode(_ enterprisecode: String, _ isold: Bool = false) -> Bool{
        let predicate = NSPredicate.init(format: "SELF MATCHES %@", isold ? MZValidateTool.validate_code_enterprise_15 : MZValidateTool.validate_code_enterprise_18)
        return predicate.evaluate(with: enterprisecode)
    }
    
    public static func validateIDCard(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
        if range.length == 1, string.count == 0{
            return true
        }
        if string != "" {
            let lowercasechar = string.first
            if (textField.text?.count ?? 0) >= 18 {
                return false
            }
            if range.location < 17 {
                if let charcode = lowercasechar?.asciiValue, charcode >= 48, charcode <= 57{
                    return true
                }else{
                    return false
                }
            }
            if range.location == 17 {
                if let charcode = lowercasechar?.asciiValue, charcode > 64, charcode < 123 {
                    if charcode == 12 || charcode == 88 {
                        let uppercasestr = string.uppercased()
                        if let str = textField.text{
                            let frontstr = str[str.startIndex...str.index(str.startIndex, offsetBy: range.location)]
                            let backstr = str[str.index(str.startIndex, offsetBy: range.location)...str.endIndex]
                            textField.text = frontstr + uppercasestr + backstr
                            return true
                        }
                        return false
                    }
                }else{
                    if let charcode = lowercasechar?.asciiValue, charcode >= 48, charcode <= 57{
                        return true
                    }else{
                        return false
                    }
                }
            }
        }
        return true
    }
    
    public static func validateEnterpriseCode(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
        if range.length == 1, string.count == 0 {
            return true
        }
        if string != ""{
            let lowercasechar = string.first
            if (textField.text?.count ?? 0) >= 18 {
                return false
            }
            if range.location <= 18 {
                if let charcode = lowercasechar?.asciiValue, ((charcode >= 48 && charcode <= 57) || (charcode >= 65 && charcode <= 90) || (charcode >= 97 && charcode <= 122)) {
                    return true
                }else{
                    return false
                }
            }
        }
        return true
    }
    
    
    public static func checkTextviewDidChange(textView: UITextView, maxCount: Int,
                                              placeholderHiddenfresh pcb: ( (Bool) -> Void)?,
                                              countfresh countf: ( (Int) -> Void)?,
                                              uifresh uif:( () -> Void)? = nil){
        guard let text:String = textView.text else{
            return
        }
        let max = maxCount
        pcb?(text.count != 0)
        if text.count > maxCount {
            let tostr = text
            let range = text.rangeOfComposedCharacterSequence(at: tostr.index(tostr.startIndex, offsetBy: max))
            if range.upperBound.hashValue == 1 {
                textView.text = String(tostr[tostr.startIndex...tostr.index(tostr.startIndex, offsetBy: max)])
            }else{
                textView.text = String(tostr[tostr.startIndex...tostr.index(tostr.startIndex, offsetBy: max-1)])
            }
            countf?(maxCount)
            uif?()
            return
        }
        let tostr = text
        var num: Int = tostr.count
        if num >= max {
            num = max
        }
        countf?(num)
        uif?()
        let lang = UIApplication.shared.textInputMode?.primaryLanguage
        if lang == "zh-Hans" {
            guard let selectedrange = textView.markedTextRange else {return}
            let postion = textView.position(from: selectedrange.start, offset: 0)
            if postion == nil {
                if tostr.count > max {
                    let range = text.rangeOfComposedCharacterSequence(at: tostr.index(tostr.startIndex, offsetBy: max))
                    if range.upperBound.hashValue == 1 {
                        textView.text = String(tostr[tostr.startIndex...tostr.index(tostr.startIndex, offsetBy: max)])
                    }else{
                        textView.text = String(tostr[tostr.startIndex...tostr.index(tostr.startIndex, offsetBy: max-1)])
                    }
                }
            }
        }else{
            if tostr.count > max {
                let range = text.rangeOfComposedCharacterSequence(at: tostr.index(tostr.startIndex, offsetBy: max))
                if range.upperBound.hashValue == 1 {
                    textView.text = String(tostr[tostr.startIndex...tostr.index(tostr.startIndex, offsetBy: max)])
                }else{
                    textView.text = String(tostr[tostr.startIndex...tostr.index(tostr.startIndex, offsetBy: max-1)])
                }
                
            }
        }
    }
}
